package com.umeox.watch.moto.gallery.ui;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.umeox.moto.common.log.Logger;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.watch.moto.dataservice.interfaces.IPullApiClient;
import com.umeox.watch.moto.dataservice.proxy.PullApiClientProxy;
import com.umeox.watch.moto.gallery.R;
import com.umeox.watch.moto.gallery.bean.Gallery;
import com.umeox.watch.moto.gallery.db.AppDataBase;
import com.umeox.watch.moto.gallery.db.model.AlbumInfo;

import java.io.File;
import java.util.List;

/**
 * Created by Rambo 2019-11-23
 * Describe:
 */
public class UploadActivity extends ThemeAppCompatActivity {


    private static final String TAG = UploadActivity.class.getSimpleName();

    private TextView mMessageTv;
    private ImageView mLoadingIv;
    private RotateAnimation mRotateAnimation;

    private static final int UPLOAD_COMPLETE = 0x10;
    private static final int FINISH_ACTIVITY = 0x12;
    private static final int UPLOAD_FAIL = 0x14;
    private List<String> mPhotos;
    private IPullApiClient mPullApiClient;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == UPLOAD_COMPLETE) {
                //全部上传完毕，通知
                Logger.i("TAG", "=================发通知了============================");
                getContentResolver().notifyChange(Gallery.CONTENT_URI, null);
                mMessageTv.setText(R.string.str_upload_completed);
                mRotateAnimation.cancel();
                mLoadingIv.clearAnimation();
                mLoadingIv.setImageResource(R.drawable.icon_upload_success);

                mHandler.sendEmptyMessageDelayed(FINISH_ACTIVITY, 1000);
            } else if (msg.what == FINISH_ACTIVITY) {
                finish();
            } else if (msg.what == UPLOAD_FAIL) {
                mMessageTv.setText(R.string.str_upload_failure);
                mRotateAnimation.cancel();
                mLoadingIv.clearAnimation();
                mLoadingIv.setImageResource(R.drawable.icon_upload_fail);

                mHandler.sendEmptyMessageDelayed(FINISH_ACTIVITY, 1000);
            }
            return false;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_upload);

        mPhotos = getIntent().getStringArrayListExtra("list");

        if (mPullApiClient == null) {
            mPullApiClient = PullApiClientProxy.fetchBinder();
        }
        mMessageTv = findViewById(R.id.tvMessage);
        mLoadingIv = findViewById(R.id.ivUploading);
        mLoadingIv.setVisibility(View.VISIBLE);
        startAnimation();

        if (mPhotos != null && mPhotos.size() > 0) {
            uploadImages(mPhotos);
        }
    }


    private void startAnimation() {
        mRotateAnimation = new RotateAnimation(0, // 起始角度
                359,// 终止的角度
                Animation.RELATIVE_TO_SELF,
                0.5f,
                Animation.RELATIVE_TO_SELF,
                0.5f);
        mRotateAnimation.setDuration(1500);
        mRotateAnimation.setInterpolator(new LinearInterpolator());
        mRotateAnimation.setRepeatCount(Animation.INFINITE);

        mLoadingIv.startAnimation(mRotateAnimation);
    }

    /**
     * 上传多文件
     *
     * @param urls
     */
    public void uploadImages(List<String> urls) {
        if (null == urls || urls.size() == 0) {
            return;
        } // 上传文件
        beginUpload(urls);
    }

    private void beginUpload(final List<String> urls) {
        Logger.i(TAG, "urls.size:" + urls.size());

        if (urls.size() <= 0) {
            // 文件全部上传完毕，这里编写上传结束的逻辑，如果要在主线程操作，最好用Handler或runOnUiThread做对应逻辑
            mHandler.sendEmptyMessageDelayed(UPLOAD_COMPLETE, 500);
            return;
        }
        final String url = urls.get(0);
        Logger.i(TAG, "url:" + url);
        if (TextUtils.isEmpty(url)) {
            urls.remove(0);
            // url为空就没必要上传了，这里做的是跳过它继续上传的逻辑。
            beginUpload(urls);
            return;
        }

        File file = new File(url);
        if (!file.exists()) {
            urls.remove(0);
            // 文件为空或不存在就没必要上传了，这里做的是跳过它继续上传的逻辑。
            beginUpload(urls);
            return;
        }

        AsyncTask.execute(() -> {
            try {
                String uploadFileUrl = mPullApiClient.uploadAlumFile(url);
                Logger.e(TAG, "uploadFileUrl:" + uploadFileUrl);
                if (!TextUtils.isEmpty(uploadFileUrl)) {
                    //更新数据库
                    AlbumInfo albumInfo = AppDataBase.getInstance().albumInfoDao().queryByImagePath(url);
                    if (albumInfo != null) {
                        albumInfo.uploadTime = System.currentTimeMillis();
                        albumInfo.imageServerPath = uploadFileUrl;
                        albumInfo.tag1 = 1;
                        long result = AppDataBase.getInstance().albumInfoDao().save(albumInfo);
                        Logger.i(TAG, "result:" + result);
                    }

                    if (!urls.isEmpty()) {
                        urls.remove(0);
                    }
                    mPhotos.remove(url);
                    beginUpload(urls);// 递归同步效果
                } else {
                    mHandler.sendEmptyMessage(UPLOAD_FAIL);
                }
            } catch (RemoteException e) {
                mHandler.sendEmptyMessage(UPLOAD_FAIL);
                e.printStackTrace();
            }
        });


    }
}
